package buffer;

/**
 * @author yangwenqi
 * @decs TODO
 * @date 2025/5/14
 * 文件拷贝
 * 1.选择使用哪一个流对象
 * 2.FileXxx 和  BufferedXxx 两者哪一个效率高
 * 文件夹拷贝
 * 使用上一题较为高效的流对象完成
 */
import java.io.*;

public class TestcopyFile {
    private static void copyFile(File sourceFile, File targetFile) {
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile));
             BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(targetFile))) {
            byte[] bytes = new byte[1024];
            int len=0;
            while ((len = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, len);
            }
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void copyFolder(File source, File target)throws IOException {

        if (!source.exists() || !source.isDirectory()) {
            throw new IOException("源目录不存在或不是有效目录: " + source.getAbsolutePath());
        }

        if (!target.exists() && !target.mkdirs()) {
            throw new IOException("无法创建目标目录: " + target.getAbsolutePath());
        }

        File[] files = source.listFiles();
        if (files == null) return;

        for (File file : files) {
            File targetEntry = new File(target, file.getName());
            if (file.isFile()) {
                copyFile(file, targetEntry);
                System.out.println("拷贝文件完成: " + file.getAbsolutePath());
            } else if (file.isDirectory()) {
                // 递归拷贝
                copyFolder(file, targetEntry);
                System.out.println("处理子目录完成: " + file.getAbsolutePath());
            }
        }
    }
    public static void main(String[] args) {
        File source = new File("D:/temp");
        File target = new File("D:/temp3");
        try {
            copyFolder(source, target);
            System.out.println("源路径: " + source.getAbsolutePath());
            System.out.println("目标路径: " + target.getAbsolutePath());
        } catch (IOException e) {
            System.err.println("文件夹拷贝失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

